//
//  OAuthViewController.swift
//  weibo
//
//  Created by 吕俊霖 on 15/11/11.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    
    // 定义一个webView属性
    let webView = UIWebView()
    let client_id = "444380539"
    let redirect_uri = "http://www.itcast.cn"
    
    
    //MARK: 监听方法
    @objc func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc func padding(){
        
        let jsString = "document.getElementById('userId').value = 'junlin912@126.com' , document.getElementById('passwd').value = 'qq9866164';"
    
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadOauthPage()
    }
    
    private func loadOauthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "padding")
        
    }
 
}


extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //协议方法 如果返回 bool  一般表示 如果为true  表示当前对象可以正常 工作  否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        
        return true
        
    }
}
